#!/bin/bash

SWNAME=mesa-freedreno
SWVER=24.3.0

# 注意安装顺序，后装者依赖前装者
DEB_PATH1=./downloads/${SWNAME}-${SWVER}.tar.xz

DIR_DESKTOP_FILES=/usr/share/applications
DSK_FILE=${SWNAME}.desktop
DSK_PATH=${DIR_DESKTOP_FILES}/${DSK_FILE}
# app_dir=/opt/apps/mesa-${SWVER}
app_dir=

action=$1
if [ "$action" == "" ]; then action=安装; fi

. ./scripts/common.sh

if [ "${action}" == "卸载" ]; then
	# echo "暂不支持卸载"
	# exit 1
	sudo apt-get purge --auto-remove -y mesa-freedreno
	rm -rf /etc/autoruns/autoruns_before_gui/mesa-freedreno.sh
else

	tmpdns=`cd /exbin && droidexec ./vm_getHostByName.sh ${GITHUB_PROXY_HOST}`
	exit_if_fail $? "DNS解析失败"
	echo "$tmpdns" >> /etc/hosts

	case "${CURRENT_VM_ARCH}" in
		"arm64")
			swUrl="${GITHUB_PROXY_HTTP}https://github.com/droidvm/mesa-freedreno-patchs/releases/download/24.3.0/mesa-24.3.0-out-arm64.tar.xz"
			download_file2 "${DEB_PATH1}" "${swUrl}"
			exit_if_fail $? "下载失败，网址：${swUrl}"
		;;
		*) exit_unsupport ;;
	esac

	# dpkg -i --force-overwrite ${DEB_PATH1}
	# exit_if_fail $? "安装失败，软件包：${DEB_PATH1}"


	echo "正在解压. . ."
	mkdir -p ${app_dir} 2>/dev/null
	tar -xJf ${DEB_PATH1} --overwrite -C ${app_dir}/
	exit_if_fail $? "安装失败，软件包：${DEB_PATH1}"


	sed -i "s|library_path\": \"|library_path\": \"${app_dir}|" ${app_dir}/usr/share/vulkan/icd.d/freedreno_icd.aarch64.json
	exit_if_fail $? "icd.json配置失败(Vulkan Installable Client Driver)"

	sudo apt-get install -y glmark2-x11
	exit_if_fail $? "glmark2 安装失败"

	# 全局变量
	[ -d /etc/autoruns/autoruns_before_gui ] || mkdir -p /etc/autoruns/autoruns_before_gui 2>/dev/null
	cat <<- EOF > ${DIR_PROFILE_D}/${SWNAME}.sh
		# RLT_DIR=/exbin/tools/zzswmgr/tmp/mesa-24.3.0-out-arm64
		# export LD_LIBRARY_PATH=$RLT_DIR/usr/lib/aarch64-linux-gnu:$RLT_DIR/usr/lib/aarch64-linux-gnu/dri
		# export MESA_LOADER_DRIVER_OVERRIDE=kgsl
		# export VK_ICD_FILENAMES=$RLT_DIR/usr/share/vulkan/icd.d/freedreno_icd.aarch64.json
		# export TU_DEBUG=noconform
		# export MESA_VK_WSI_PRESENT_MODE=fifo

		export MESA_LOADER_DRIVER_OVERRIDE=kgsl
		export VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/freedreno_icd.aarch64.json
		export TU_DEBUG=noconform
		export MESA_DEBUG=1
		export LIBGL_DEBUG=verbose
		export MESA_LOG_FILE=~/ms.log
	EOF

	# patch for xfce4
	XFCE_CONF_XML=${ZZ_USER_HOME}/.config/xfce4/xfconf/xfce-perchannel-xml/xfwm4.xml
	if [ -f "${XFCE_CONF_XML}" ]; then
		sed -i 's|property name="vblank_mode" type="string" value="auto"|property name="vblank_mode" type="string" value="off"|g'  ${XFCE_CONF_XML}
	fi

	gxmessage -title "提示"     $'\n安装完成，重启后生效！\n\n'  -center

fi
